
package com.freeme.cameraplugin.watermarkmode.utils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.json.JSONException;
import org.json.JSONObject;
import com.freeme.cameraplugin.watermarkmode.model.WatermarkItemInfo;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.NinePatch;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.NinePatchDrawable;
import android.os.Environment;
import android.util.Log;
import android.view.WindowManager;

public final class WatermarkUtil {
    public static final String HTTP_AREA = "http://service-fomultimedia.yy845.com:2860";
    public final static int WATERWARK_TYPE_CODE = 100001;
    public final static int CHILDMODE_TYPE_CODE = 100101;
    public final static int POSE_TYPE_CODE = 100201;
    public final static int JIGSAW_TYPE_CODE = 100301;
    public final static int VERSION_NUM_TYPE_CODE = 100601;
    public final static int ITEM_CNT_TYPE_CODE = 100701;
    public final static int REQUEST_ITEM_MAX = 50;
    public static final String SEPARATOR = "_";
    public static final String PICTURE_SUFFIX = ".png";
    public static final String PICTURE_SUFFIX_DOC9 = ".9.png";
    public static final String AUDIO_SUFFIX = ".ogg";
    public static final String THUMBNAIL_FILE_ID = "thumbnail";
    public static final String PRIMITIVE_FILE_ID = "primitive";
    public static final String INFO_FILE_ID = "info";
    public static final String WATERWARK_PATH = "/.ElementsCenter/WaterMark/";
    public static final String CHILDMODE_PATH = "/.ElementsCenter/ChildMode/";
    public static final String POSEMODE_PATH = "/.ElementsCenter/PoseMode/";
    public static final String JIGSAW_PATH = "/.ElementsCenter/JigSaw/";
    public static final String DOWLOAD_CACHE_PATH = "/.ElementsCenter/download/cache/";
    public static final String WATERWARK_TYPE_ARRAY[] = {
            "travel", "food", "catchword", "regards", "selfie", "mood"
    };

    public static final String POSEMODE_TYPE_ARRAY[] = {
            "male", "female", "family"
    };

    public static final String[] TYPE_ARRAY = {
            "watermark", "childmode", "posemode", "jigsaw",
    };

    public static String getDownloadCachePath() {
        return getSDPath() + DOWLOAD_CACHE_PATH;
    }

    public static String utf8UrlEncode(String text) {
        StringBuffer result = new StringBuffer();
        for (int i = 0; i < text.length(); i++) {
            char c = text.charAt(i);
            if (c >= 0 && c <= 255) {
                result.append(c);
            } else {
                byte[] b = new byte[0];
                try {
                    b = Character.toString(c).getBytes("UTF-8");
                } catch (Exception ex) {
                }
                for (int j = 0; j < b.length; j++) {
                    int k = b[j];
                    if (k < 0) k += 256;
                    result.append("%" + Integer.toHexString(k).toUpperCase());
                }
            }
        }
        return result.toString();
    }

    public static String utf8UrlDecode(String text) {
        String result = "";
        int p = 0;
        if (text != null && text.length() > 0) {
            text = text.toLowerCase();
            p = text.indexOf("%e");
            if (p == -1) return text;
            while (p != -1) {
                result += text.substring(0, p);
                text = text.substring(p, text.length());
                if (text == "" || text.length() < 9) return result;
                result += codeToWord(text.substring(0, 9));
                text = text.substring(9, text.length());
                p = text.indexOf("%e");
            }
        }
        return result + text;
    }

    private static String codeToWord(String text) {
        String result;
        if (utf8CodeCheck(text)) {
            byte[] code = new byte[3];
            code[0] = (byte) (Integer.parseInt(text.substring(1, 3), 16) - 256);
            code[1] = (byte) (Integer.parseInt(text.substring(4, 6), 16) - 256);
            code[2] = (byte) (Integer.parseInt(text.substring(7, 9), 16) - 256);
            try {
                result = new String(code, "UTF-8");
            } catch (UnsupportedEncodingException ex) {
                result = null;
            }
        } else {
            result = text;
        }
        return result;
    }

    private static boolean utf8CodeCheck(String text) {
        String sign = "";
        if (text.startsWith("%e")) for (int i = 0, p = 0; p != -1; i++) {
            p = text.indexOf("%", p);
            if (p != -1) p++;
            sign += p;
        }
        return sign.equals("147-1");
    }

    public static boolean isUtf8Url(String text) {
        text = text.toLowerCase();
        int p = text.indexOf("%");
        if (p != -1 && text.length() - p > 9) {
            text = text.substring(p, p + 9);
        }
        return utf8CodeCheck(text);
    }

    public static List<String> getFileNameAndPageType(int typeCode, int pageType) {
        ArrayList<String> retList = new ArrayList<String>();
        String fileRoot = "";
        String pageTypeCode = "";
        String thumbnailFileName = "";
        String primitiveFileName = "";
        String infoFileName = INFO_FILE_ID;
        switch (typeCode) {
            case WatermarkUtil.WATERWARK_TYPE_CODE:
                fileRoot = WatermarkUtil.getSDPath() + WatermarkUtil.WATERWARK_PATH;
                pageTypeCode = WATERWARK_TYPE_ARRAY[pageType];
                if (pageTypeCode.equals("selfie")) {
                    primitiveFileName = WatermarkUtil.PRIMITIVE_FILE_ID
                            + WatermarkUtil.PICTURE_SUFFIX_DOC9;
                } else {
                    primitiveFileName = WatermarkUtil.PRIMITIVE_FILE_ID
                            + WatermarkUtil.PICTURE_SUFFIX;
                }
                thumbnailFileName = WatermarkUtil.THUMBNAIL_FILE_ID + WatermarkUtil.PICTURE_SUFFIX;
                break;
            case WatermarkUtil.CHILDMODE_TYPE_CODE:
                fileRoot = WatermarkUtil.getSDPath() + WatermarkUtil.CHILDMODE_PATH;
                pageTypeCode = "childmode";
                thumbnailFileName = WatermarkUtil.THUMBNAIL_FILE_ID + WatermarkUtil.PICTURE_SUFFIX;
                primitiveFileName = WatermarkUtil.PRIMITIVE_FILE_ID + WatermarkUtil.AUDIO_SUFFIX;
                break;
            case WatermarkUtil.POSE_TYPE_CODE:
                fileRoot = WatermarkUtil.getSDPath() + WatermarkUtil.POSEMODE_PATH;
                pageTypeCode = POSEMODE_TYPE_ARRAY[pageType];
                thumbnailFileName = WatermarkUtil.THUMBNAIL_FILE_ID + WatermarkUtil.PICTURE_SUFFIX;
                primitiveFileName = WatermarkUtil.PRIMITIVE_FILE_ID + WatermarkUtil.PICTURE_SUFFIX;
                break;
            case WatermarkUtil.JIGSAW_TYPE_CODE:
                fileRoot = WatermarkUtil.getSDPath() + WatermarkUtil.JIGSAW_PATH;
                pageTypeCode = "jigsaw";
                thumbnailFileName = WatermarkUtil.THUMBNAIL_FILE_ID + WatermarkUtil.PICTURE_SUFFIX;
                primitiveFileName = WatermarkUtil.PRIMITIVE_FILE_ID + WatermarkUtil.PICTURE_SUFFIX;
                break;
            default:
                break;
        }

        retList.add(fileRoot);
        retList.add(pageTypeCode);
        retList.add(thumbnailFileName);
        retList.add(primitiveFileName);
        retList.add(infoFileName);
        return retList;
    }

    public static String getSDPath() {
        File sdDir = null;
        boolean sdCardExist = Environment.getExternalStorageState().equals(
                android.os.Environment.MEDIA_MOUNTED);
        if (sdCardExist) {
            sdDir = Environment.getExternalStorageDirectory();
        } else {
            return null;
        }
        return sdDir.toString();
    }

    private static boolean isFileExist(String fileName) {
        boolean isExist = false;
        File file = new File(fileName);
        if (file.exists() && file.isFile()) {
            isExist = true;
        }
        return isExist;
    }

    private static void deleteFile(String fileName) {
        File file = new File(fileName);
        if (file.exists() && file.isFile()) {
            file.delete();
        }
    }

    public static WatermarkItemInfo jsonStrToItemInfo(String jStr) {
        try {
            JSONObject jObj = new JSONObject(jStr.trim());
            String type = String.valueOf(jObj.get("type"));
            int layoutId = Integer.parseInt(String.valueOf(jObj.get("layoutId")));
            int colorId = Integer.parseInt(String.valueOf(jObj.get("colorId")));
            int thumbnailId = Integer.parseInt(String.valueOf(jObj.get("thumbnailId")));
            int primitiveId = Integer.parseInt(String.valueOf(jObj.get("primitiveId")));
            int promptId = Integer.parseInt(String.valueOf(jObj.get("promptId")));
            int color = Integer.parseInt(String.valueOf(jObj.get("color")));
            String thumbnailUrl = String.valueOf(jObj.get("thumbnailUrl"));
            String primitiveUrl = String.valueOf(jObj.get("primitiveUrl"));
            String prompt = String.valueOf(jObj.get("prompt"));
            String name = String.valueOf(jObj.get("name"));
            WatermarkItemInfo itemInfo = new WatermarkItemInfo();
            itemInfo.type = type;
            itemInfo.layoutId = layoutId;
            itemInfo.colorId = colorId;
            itemInfo.thumbnailId = thumbnailId;
            itemInfo.primitiveId = primitiveId;
            itemInfo.promptId = promptId;
            itemInfo.thumbnailUrl = thumbnailUrl;
            itemInfo.primitiveUrl = primitiveUrl;
            itemInfo.prompt = prompt;
            itemInfo.color = color;
            itemInfo.name = name;
            return itemInfo;
        } catch (JSONException e) {
            Log.i("error", "JSONException:" + e.toString());
            e.printStackTrace();
            return null;
        }
    }

    public static String itemInfoToJsonStr(WatermarkItemInfo itemInfo) {
        JSONObject jObj = new JSONObject();
        try {
            jObj.put("type", itemInfo.type);
            jObj.put("layoutId", itemInfo.layoutId);
            jObj.put("colorId", itemInfo.colorId);
            jObj.put("thumbnailId", itemInfo.thumbnailId);
            jObj.put("primitiveId", itemInfo.primitiveId);
            jObj.put("promptId", itemInfo.promptId);
            jObj.put("color", itemInfo.color);
            jObj.put("thumbnailUrl", itemInfo.thumbnailUrl);
            jObj.put("primitiveUrl", itemInfo.primitiveUrl);
            jObj.put("prompt", itemInfo.prompt);
            jObj.put("name", itemInfo.name);
            String jStr = jObj.toString();
            Log.i("list", "jStr:" + jStr);
            return jStr;
        } catch (JSONException e) {
            Log.i("error", "JSONException:" + e.toString());
            e.printStackTrace();
            return null;
        }
    }

    public static boolean isFileExistByFileUrl(String fileUrl) {
        try {
            Log.i("file", "isFileExistByFileUrl,fileUrl:" + fileUrl);
            URL url = new URL(fileUrl);
            String fileName = utf8UrlDecode(url.getFile());
            Log.i("file", "isFileExistByFileUrl fileName:" + fileName);
            return isFileExist(fileName);
        } catch (MalformedURLException e) {
            e.printStackTrace();
            return false;
        }
    }

    private static byte[] loadByteArrayUrl(String path) {

        ByteArrayOutputStream outputStream = null;
        try {
            URL url = new URL(path);
            InputStream inputStream = (InputStream) url.getContent();

            outputStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, len);
            }
            outputStream.close();
            inputStream.close();

        } catch (MalformedURLException e1) {
            e1.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return outputStream != null ? outputStream.toByteArray() : null;
    }

    private static final int MAX_CACHE_SIZE = 5;
    private static Map<String, Bitmap> sCache = new HashMap<String, Bitmap>();
    private static List<String> sFileUrlList = new ArrayList<String>();

    public static Bitmap getBitmapByFileUrl(String fileUrl) {
        try {
            if (sFileUrlList.size() == MAX_CACHE_SIZE) {
                String pFileUrl = sFileUrlList.get(0);
                sFileUrlList.remove(0);
                Bitmap pBitmap = sCache.get(pFileUrl);
                if (pBitmap != null) {
                    pBitmap.recycle();
                }
                sCache.remove(pFileUrl);
            }
            Bitmap currBp = sCache.get(fileUrl);
            if (currBp == null) {
                URL url = new URL(fileUrl);
                String fileName = utf8UrlDecode(url.getFile());
                Log.i("file", "fileName:" + fileName);
                Bitmap bitmap = decodeFromFile(fileName);
                sCache.put(fileUrl, bitmap);
                sFileUrlList.add(fileUrl);
                return bitmap;
            }
            return currBp;

        } catch (MalformedURLException e) {
            e.printStackTrace();
            Log.i("error", "getBitmapByFileUrl e:" + e.toString());
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static Bitmap decodeFromStream(InputStream in) throws Exception {
        Bitmap srcBm = BitmapFactory.decodeStream(in);
        return srcBm;
    }

    public static Bitmap decodeFromFile(String path) throws Exception {
        InputStream in = new FileInputStream(path);
        Bitmap bm = decodeFromStream(in);
        in.close();
        return bm;
    }

    public static Drawable bitmapToNinePatchDrawable(Context context, Bitmap bitmap) {
        final byte[] chunk = bitmap.getNinePatchChunk();
        if (NinePatch.isNinePatchChunk(chunk)) {
            NinePatchDrawable drawable = new NinePatchDrawable(context.getResources(), bitmap,
                    chunk, NinePatchChunk.deserialize(chunk).mPaddings, null);
            Log.i("file", "NinePatchDrawable");
            return drawable;
        } else {
            return new BitmapDrawable(bitmap);
        }
    }

    public static String getResolution(Context context) {
        String ret = "";
        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        int width = wm.getDefaultDisplay().getWidth();
        int height = wm.getDefaultDisplay().getHeight();
        if (width > height) {
            ret = width + "x" + height;
        } else {
            ret = height + "x" + width;
        }
        return ret;
    }
}
